package com.wgj.android.ui.activity;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.os.Environment;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.widget.TableLayout;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.jiaai.xui.XUI;
import com.jiaai.xui.base.XActivity;
import com.jiaai.xui.cache.XCache;
import com.jiaai.xui.icon.utils.IconUtils;
import com.jiaai.xui.utils.XAppUtils;
import com.jiaai.xui.utils.XThemeUtils;
import com.jiaai.xui.utils.http.HttpCallBack;
import com.jiaai.xui.utils.http.XHttp;
import com.jiaai.xui.view.widget.XAlertMsgDialog;
import com.jiaai.xui.view.widget.XToast;
import com.jiaai.xui.view.widget.tablayout.CommonTabLayout;
import com.jiaai.xui.view.widget.tablayout.TabEntity;
import com.jiaai.xui.view.widget.tablayout.listener.CustomDrawableTabEntity;
import com.wgj.android.R;
import com.wgj.android.entity.Version;
import com.wgj.android.entity.YoukuToken;
import com.wgj.android.events.LocationEvent;
import com.wgj.android.fragment.HomeFragment;
import com.wgj.android.fragment.MyFragment;
import com.wgj.android.fragment.ServerFragment;
import com.wgj.android.http.OKHttpEngine;
import com.wgj.android.http.WGJAPI;
import com.wgj.android.utils.CacheUtils;
import com.wgj.android.utils.DownloadAppUtils;
import com.wgj.android.utils.SMFrameCallback;
import com.wgj.android.utils.fonat.IconFonat;
import com.wgj.android.youku.Config;
import com.wgj.android.zfp.WXCheckService;
import com.wgj.android.zfp.WXCleanService;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import cn.jpush.android.api.JPushInterface;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MultipartBody;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import static okhttp3.internal.Util.EMPTY_REQUEST;


public class MainActivity extends XActivity {
   // public LocationClient mLocationClient;
    private CommonTabLayout  commonTabLayoutl;
    private ArrayList<Fragment> mFragments = new ArrayList<>();
    private ArrayList<CustomDrawableTabEntity> mTabEntities = new ArrayList<>();
    private TableLayout tableLayout;


    @Override
    public int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    public void initData(Bundle bundle) {

        JPushInterface.setAlias(getApplicationContext(),100, CacheUtils.getMember().getM_id());
        /*if(mLocationClient==null){
            //声明LocationClient类
            mLocationClient = new LocationClient(getApplicationContext());
            //注册监听函数
            mLocationClient.registerLocationListener(listener);
            LocationClientOption option = new LocationClientOption();
            option.setIsNeedAddress(true);
            mLocationClient.setLocOption(option);
            mLocationClient.start();
        }*/

    }

    @Override
    public void initView() {
        //getToken();//获取优酷上传视频的有效期30天


        Drawable[] unselectIcon=new Drawable[]{
                IconUtils.getDrawble(this, IconFonat.Icon.home_on, XUI.getColor(R.color.tab_un_select),16),
                IconUtils.getDrawble(this, IconFonat.Icon.icon_fuwu,  XUI.getColor(R.color.tab_un_select),16),
                IconUtils.getDrawble(this, IconFonat.Icon.my_on,  XUI.getColor(R.color.tab_un_select),16)
        };
        int color= XThemeUtils.getColorPrimary(this);
        Drawable[] selectIcon=new Drawable[]{
                IconUtils.getDrawble(this, IconFonat.Icon.home_select,color,16),
                IconUtils.getDrawble(this, IconFonat.Icon.icon_fuwu1,color,16),
                IconUtils.getDrawble(this, IconFonat.Icon.my_select, color,16)
        };
        commonTabLayoutl=findViewById(R.id.tablayout);
        mFragments.add( new HomeFragment());
      //  mFragments.add( WGJWebFragment.getInstance(new WebConfig("file:///android_asset/web/shoppingmall.html","",0)));

        //mFragments.add(new ServerFragment());
        mFragments.add(new MyFragment());

        mTabEntities.add(new TabEntity("首页",selectIcon[0],unselectIcon[0]));
       //mTabEntities.add(new TabEntity("服务",selectIcon[1],unselectIcon[1]));
        mTabEntities.add(new TabEntity("我的",selectIcon[2],unselectIcon[2]));

        commonTabLayoutl.setDrawbleTabData(mTabEntities,this,R.id.contentView,mFragments);
        commonTabLayoutl.setCurrentTab(0);
    }

    @Override
    protected void onDestroy() {
       // mLocationClient.unRegisterLocationListener(listener); //注销掉监听
        //mLocationClient.stop(); //停止定位服务
        super.onDestroy();
    }



    /**
     * 获取apk包的信息：版本号，名称，图标等
     * @param absPath apk包的绝对路径
     * @param context
     */
    public PackageInfo apkInfo(String absPath,Context context) {

        PackageManager pm = context.getPackageManager();
        PackageInfo pkgInfo = pm.getPackageArchiveInfo(absPath,PackageManager.GET_ACTIVITIES);
        if (pkgInfo != null) {
            ApplicationInfo appInfo = pkgInfo.applicationInfo;
        /* 必须加这两句，不然下面icon获取是default icon而不是应用包的icon */
            appInfo.sourceDir = absPath;
            appInfo.publicSourceDir = absPath;
            String appName = pm.getApplicationLabel(appInfo).toString();// 得到应用名
            String packageName = appInfo.packageName; // 得到包名
            String version = pkgInfo.versionName; // 得到版本信息
        /* icon1和icon2其实是一样的 */
            Drawable icon1 = pm.getApplicationIcon(appInfo);// 得到图标信息
            Drawable icon2 = appInfo.loadIcon(pm);
            String pkgInfoStr = String.format("PackageName:%s, Vesion: %s, AppName: %s", packageName, version, appName);
            Log.i("", String.format("PkgInfo: %s", pkgInfoStr));
        }
        return pkgInfo;
    }

    /*****
     *
     * 定位结果回调，重写onReceiveLocation方法
     *
     */
   /* private BDAbstractLocationListener listener = new BDAbstractLocationListener() {

        @Override
        public void onReceiveLocation(BDLocation location) {
            // TODO Auto-generated method stub
            if (null != location && location.getLocType() != BDLocation.TypeServerError) {
                // 国家名称
               String str =  location.getCountry();
                // 城市
                String str1 =location.getCity();
                // 城市编码
                String str2 =location.getCityCode();
                LocationEvent event = new LocationEvent();
                event.setName(str1);
                EventBus.getDefault().postSticky(event);
            }
        }

    };*/


    @Override
    protected void onResume() {
        super.onResume();

    }
    private void getToken(){
        /*Map<String,Object> params =new HashMap<>();
        params.put("client_id", Config.client_id);
        params.put("grant_type","refresh_token");
        params.put("refresh_token","d7586aaa46e9eb78f54fddaa9068f1a9");
        RequestBody body = EMPTY_REQUEST;
        if (null != params&&!params.isEmpty()) {
            MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
            for (String key : params.keySet()) {
                Object value = params.get(key);
                builder.addFormDataPart(key, value.toString());
            }
            body = builder.build();
        }

        final Request request = new Request.Builder()
                .url("https://api.youku.com/oauth2/token.json")
                .post(body)
                .build();
        new OKHttpEngine().client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                XToast.info("异常");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                com.alibaba.fastjson.JSONObject restResult = JSON.parseObject(response.body().string());
                YoukuToken youkuBean = new Gson().fromJson(restResult.toJSONString(),YoukuToken.class);
                CacheUtils.cacheYouKuToken(youkuBean);
            }
        });*/
    }
    private Long time = 0L;

    @Override
    public void onBackPressed() {
        if (System.currentTimeMillis() - time > 2000) {
            time = System.currentTimeMillis();
            XToast.info("再按一次退出");
            return;
        }
        if (System.currentTimeMillis() - time < 2000) {
            super.onBackPressed();
        }
    }
}
